import pgzrun

WIDTH = 1000
HEIGHT = 700
pen = Actor('pen')
eraser = Actor('eraser')
flag = 0  # 表示程序状态
# flag为0或1时pen为笔，flag为0时鼠标未按下，为1时鼠标按下
# flag为2或3时pen为橡皮，flag为2时鼠标未按下，为3时鼠标按下
pen_clones = []  # 画笔或史蒂夫的克隆体，在画布上留下的痕迹


def draw():
    global flag
    screen.fill([16, 64, 32])  # 将背景设为绿色
    if flag == 0 or flag == 1:
        pen.draw()
    for p in pen_clones:
        p.draw()
    if flag == 2 or flag == 3:
        eraser.draw()


def on_mouse_down(button):  # 按下鼠标时执行
    global flag
    if button == mouse.LEFT:
        if flag == 0:
            flag = 1
        if flag == 2:
            flag = 3


def on_mouse_up(button):  # 松开鼠标时执行
    global flag
    if button == mouse.LEFT:
        if flag == 1:
            flag = 0
        if flag == 3:
            flag = 2


def on_mouse_move(pos):  # 移动鼠标时执行
    if flag == 0 or flag == 1:
        pen.pos = pos
    else:
        eraser.pos = pos


def on_key_down(key):
    global flag
    # 按空格键切换画笔和橡皮
    if key == key.SPACE:
        if flag == 0 or flag == 1:
            flag = 2
        else:
            flag = 0
    # 按1,2键切换画笔和史蒂夫
    if key == key.K_1:
        pen.image = 'pen'
    if key == key.K_2:
        pen.image = 'steve'


def update():
    global flag
    if flag == 1:
        pen_clone = Actor(pen.image)
        pen_clone.pos = pen.pos
        pen_clones.append(pen_clone)
    if flag == 3:  # 画笔克隆体碰到橡皮时消失
        for p in pen_clones:
            if p.colliderect(eraser):
                pen_clones.remove(p)


pgzrun.go()
